package com.StarStudio.Controller;

import com.StarStudio.Service.CouponsService;
import com.StarStudio.Service.RemoteFileService;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.QueryPageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
//@RequestMapping("/coupons")
public class CouponsController {

    @Autowired
    CouponsService couponsService;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 条件查询 优惠券分页接口
     * @param coupons 优惠券对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page")
    public PageResult page(Coupons coupons){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Coupons> couponsList;
        long allRecordNumber;
        try {
            couponsList = couponsService.findCouponsList(coupons);
            allRecordNumber = couponsService.findAllRecordNumber();
            pageInfo = new PageInfo<>(couponsList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(),couponsList,allRecordNumber);
    }

    /**
     * 获取优惠券简要信息集合
     * @return 结果对象 Result
     */
    @GetMapping("/choose_info")
    public Result getCouponsChooseResultList(){
        List<CouponsChooseResult> couponsChooseResults;
        try {
            couponsChooseResults =  couponsService.getCouponsChooseResultList();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_COUPONS_INFO_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_COUPONS_INFO_SUCCESS,couponsChooseResults);
    }


    /**
     * 导出优惠券信息到 Excel表格
     * @param response http响应
     * @param coupons 优惠券对象
     */
    @Log(title = "优惠券管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Coupons coupons) {
        List<Coupons> list = couponsService.findCouponsList(coupons);
        ExcelUtil<Coupons> util = new ExcelUtil<>(Coupons.class);
        util.exportExcel(response, list, "优惠券数据");
    }

    /**
     * 根据优惠券ID删除优惠券（可单个删除也可批量删除）
     * @param Ids 待删除的优惠券ID
     * @return 结果对象 Result
     */
    @Log(title = "优惠券管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{Ids}")
    public Result deleteCoupons(@PathVariable String Ids){
        try {
            if (Ids.contains(",")){
                String[] Id = Ids.split(",");
                for (String IdStr : Id) {
                    couponsService.DeleteCouponsById(Long.parseLong(IdStr));
                }
            }else {
                couponsService.DeleteCouponsById(Long.parseLong(Ids));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_COUPONS_SUCCESS);
    }

    /**
     * 优惠券概览图片上传
     * @param file 文件对象
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.IMPORT)
    @PostMapping("/avatar")
    public Result avatar(@RequestParam("avatarfile") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return new Result(HttpStatusCode.ERROR,"文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return new Result(HttpStatusCode.ERROR,"文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getUrl();
            return new Result(HttpStatusCode.SUCCESS, MessageConstant.UPLOAD_IMAGE_SUCCESS, url);
        }
        return new Result(HttpStatusCode.ERROR, MessageConstant.UPLOAD_IMAGE_FAIL);
    }

    /**
     * 新增优惠券
     * @param coupons 优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "优惠券管理", businessType = BusinessType.INSERT)
    @PostMapping("/post")
    public Result addCoupons(@RequestBody Coupons coupons){
        try {
            couponsService.addCoupons(coupons);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_COUPONS_SUCCESS);
    }

    /**
     * 修改优惠券
     * @param coupons 优惠券对象
     * @return 结果对象 Result
     */
    @Log(title = "优惠券管理", businessType = BusinessType.UPDATE)
    @PutMapping("/put")
    public Result updateCoupons(@RequestBody Coupons coupons){
        try {
            couponsService.updateCoupons(coupons);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_COUPONS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_COUPONS_SUCCESS);
    }

    /**
     * 根据字符串模糊匹配商家名称
     * @param name 匹配字符串
     * @return 结果对象 Result
     */
    @GetMapping("/store_name/{name}")
    public Result getLikeStoreNames(@PathVariable String name){
        List<String> list;
        try {
            list = couponsService.findLikeStoreName(name);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_STORE_NAMES_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_STORE_NAMES_SUCCESS,list);
    }

    /*
     * 远程调用接口
     */
    @RequestMapping("/findByCouponId/{id}")
    Coupons findByCoupon_id(@PathVariable(value = "id") long id){
        return couponsService.findByCoupon_id(id);
    }

    /*
     * 远程调用接口
     */
    @RequestMapping("/StockByCouponsId/{couponsId}")
    int findStockByCouponsId(@PathVariable(value = "couponsId") long couponsId){
        return couponsService.findStockByCouponsId(couponsId);
    }

    /*
     * 远程调用接口
     */
    @RequestMapping("/updateStockById/{couponsId}/{stock}")
    void updateStockById(@PathVariable(value = "couponsId") long couponsId,@PathVariable(value = "stock") int stock){
        couponsService.updateStockById(couponsId,stock);
    }

    @RequestMapping("/ByCouponsItemId/{id}")
    Coupons findByCoupons_Item_Id(@PathVariable(value = "id") long id){
        return couponsService.findByCoupons_item_id(id);
    }
}
